<template>
	<!-- 轮播图组件，配置，{
			dir，wh 		方向和设置ul的宽还是高
			speed 			速度
			point 			原点
			ctrl 				控制器
	} -->
	<div 
		class="box" 
		v-if="len>0" 
		@mouseenter="autoStop" 
		@mouseleave="autoPlay" 
		>
		<ul class="imgs" :class="{ts: index}" ref="box" :style="config">
			<li v-for="(item,i) in banner.items" :key="item.id" :style="liWH">
				<img v-if="item.img" :src="item.img" />
				<div v-else class="text">{{ item.text }}</div>
			</li>
			<li :style="liWH">
				<img v-if="false" :src="banner.items[0].img" />
				<div v-else class="text">{{ banner.items[0].text }}</div>
			</li>
		</ul>
		<ul class="points" v-if="banner.config.point">
			<li v-for="(item,i) in len" :key="i" @click="index = i" :class="index == i ? 'active' : ''"></li>
		</ul>
	</div>
</template>

<script>
export default {
	props:{
		banner : {
			type : Object,
			required : true
		}
	},
	data(){
		return {
			index: 0,
			timer: '',
			config: {
				left: '',
				top: ''
			},
			liWH: {
				width: '',
				height: ''
			}
		}
	},
	computed:{
		len(){
			return this.banner.items.length;
		},
		dir(){	// 保存方向，方便使用
			return this.banner.config.dir || 'left';
		},
		wh(){
			return this.banner.config.wh || 'width';
		}
	},
	watch:{
		index(val){
			this.config[this.dir] = -this.index * 100 + '%';
			setTimeout(()=>{
				if(this.index == this.len){
					this.index = 0;
					this.config[this.dir] = '0%';
				}
			}, this.banner.config.speed-20)
			
		}
	},
	methods:{
		autoPlay(){
			if (this.timer) return;
			this.timer = setInterval(()=>{
				this.index = (this.index+1) % (this.len+1);
			}, this.banner.config.speed)
		},
		autoStop(){
			clearInterval(this.timer);
			this.timer = null;
		}
	},
	mounted(){
		// 初始化轮播图ul的left和width,
		let sum = this.len+1;
		this.config[this.dir] = '0%';
		this.$refs.box.style[this.wh] = sum * 100 + '%';
		this.liWH[this.wh] = 100 / sum + '%';
		this.autoPlay();
	},
	destroyed(){
		this.autoStop();
	}
}
</script>

<style lang="less" scoped>
.box{
	position: relative;
	width: 100%;
	height: 100%;
	font-size: 0;
	overflow: hidden;
	.imgs{
		position: relative;
		min-height: 100%;
		min-width: 100%;
		li{
			display: inline-block;
			width: 100%;
			height: 100%;
			vertical-align: top;
			cursor: pointer;
			.text{
				text-align: center;
				font-size: 14px;
			}
		}
	}
	.ts{
		transition: .8s;
	}
	.points{
		position: absolute;
		left: 50%;
		bottom: 10%;
		transform: translateX(-50%);
		height: 12px;
		line-height: 12px;
		background-color: rgba(255,255,255,.3);
		border-radius: 6px;
		li{
			display: inline-block;
			margin: 2px;
			width: 8px;
			height: 8px;
			border-radius: 50%;
			background-color: #fff;
			cursor: pointer;
		}
		li.acitve{
			background-color: #f40;
		}
	}
}
</style>
